package com.eatsystem.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.eatsystem.common.Result;
import com.eatsystem.entity.User;
import com.eatsystem.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

//    @Value("${spring.mail.username}")
//    private String mailFrom;

    @Autowired
    private UserService userService;

//    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
//    @Autowired
//    private JavaMailSenderImpl mailSender;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     *
     * @param user
     * @return
     */
    /**@PostMapping("/sendMsg") public Result<String> sendMsg(@RequestBody User user, HttpSession session) {

    //获取手机号
    String phone = user.getPhone();

    if (StringUtils.isNotEmpty(phone)) {
    //生成随机的4位验证码
    String code = ValidateCodeUtils.generateValidateCode(4).toString();
    log.info("code = {}", code);

    //调用短信服务api发送短信
    //SMSUtils.sendMessage("瑞吉外卖","",phone,code);

    //使用邮箱发送验证码
    //SimpleMailMessage codeMsg = new SimpleMailMessage();
    //codeMsg.setFrom(mailFrom);
    //codeMsg.setSubject("验证码");
    //codeMsg.setText("这是您的验证码："+code);
    //codeMsg.setTo(phone);
    //mailSender.send(codeMsg);
    //需要将生成的验证码保存到Session
    //session.setAttribute(phone, code);

    //将生成的验证码缓存到Redis方法中，并设置有效期
    redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

    return Result.success("验证码发送成功");
    }
    return Result.error("发送失败");
    }**/


    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result<User> register(@RequestBody User user) {
        log.info(user.toString());
        //构造查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //select phone from user where phone = ?
        queryWrapper.eq(User::getPhone, user.getPhone());
        User us = userService.getOne(queryWrapper);
        //判断当前号码是否已存在
        if (us == null) {
            //不存在时注册成功
            userService.saveUser(user);
            return Result.success(user);
        } //当存在时注册失败
        return Result.error("电话号码已存在");
    }

    /**
     * 移动端用户登录(验证码版本)
     *
     * @param map
     * @param session
     * @return
     */
    /** @PostMapping("/login") public Result<User> login(@RequestBody Map map, HttpSession session) {

    log.info(map.toString());

    //获取地址
    String phone = map.get("phone").toString();
    //获得验证码
    String code = map.get("code").toString();
    //从session中获取保存的验证码
    //Object codeInSession = session.getAttribute(phone);
    //从Redis中获取缓存的验证码
    Object codeInSession = redisTemplate.opsForValue().get(phone);

    //进行验证码比对
    if (codeInSession != null && codeInSession.equals(code)) {
    //如果能够比对成功，说明登录成功

    LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(User::getPhone, phone);

    User user = userService.getOne(queryWrapper);
    //            if (user == null) {
    //                //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
    //                user = new User();
    //                user.setPhone(phone);
    //                user.setStatus(1);
    //                userService.save(user);
    //            }
    session.setAttribute("user", user.getId());
    //如果用户登录成功，删除redis中缓存的验证码
    redisTemplate.delete(phone);
    return Result.success(user);
    }
    return Result.error("登录失败");
    }**/

    /**
     * 移动端用户登录（使用账号密码登录）
     */
    @PostMapping("/login")
    public Result<User> login(@RequestBody User user, HttpServletRequest request) {
        log.info(user.toString());

        //对密码进行加密处理
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //根据手机查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, user.getPhone());
        User us = userService.getOne(queryWrapper);
        //如果不存在直接返回结果
        if (us == null) {
            return Result.error("该用户未注册");
        }
        //密码对比,如果不一致返回失败结果
        if (!us.getPassword().equals(password)) {
            return Result.error("账户名或密码错误");
        }
        //查看用户状态，如果被锁定返回失败结果
        if (us.getStatus() == 0) {
            return Result.error("账户已封锁");
        }
        //登录成功，将用户存入session并返回登录结果
        request.getSession().setAttribute("user", us.getId());
        return Result.success(us);
    }


    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @PostMapping("/loginout")
    public Result<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return Result.success("退出登录成功");
    }
}
